package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.property.PropertyAutoWithdrawDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyWithdrawGetDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.paymenthub.IPropertyBankCardManageServiceClient;
import com.itlong.cloud.paymenthub.IPropertyWithdrawServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyUserServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <desc>
 *      物业提现服务-提现管理模块聚合Controller。
 * </desc>
 * @createDate 2018/09/23
 */
@RestController
@RequestMapping(path = "/finance/propertyWithdraw")
public class PropertyWithdrawController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(PropertyWithdrawController.class);

    @Autowired
    IPropertyWithdrawServiceClient iPropertyWithdrawServiceClient;

    @Autowired
    IPropertyUserServiceClient iPropertyUserServiceClient;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Autowired
    IPropertyBankCardManageServiceClient iPropertyBankCardManageServiceClient;

    /**
     * <desc>
     *      分页查询提现列表
     * <desc/>
     *
     * @param propertyAccountGetDTO 查询未缴费数据
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/23
     */
    @RequestMapping(path = "getWithdrawByPage", method = RequestMethod.POST)
    @ResponseBody
    public Object getWithdrawByPage(PropertyWithdrawGetDTO propertyAccountGetDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyAccountGetDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWithdrawGetDTO.class, request);
            //判断使用者是否有权限
            if (!this.checkRole(propertyAccountGetDTO.getLoginUserId(),propertyAccountGetDTO.getToken())) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_USER_ROLE_ERR.getErrorCode());
            }
            //请求对象不能为空
            if(null == propertyAccountGetDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<PropertyWithdrawVO> result =
                    iPropertyWithdrawServiceClient.getWithdrawByPage(propertyAccountGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_提现服务_查询提现信息getWithdrawByPage】查询提现信息失败"), e);
        }
    }

    /**
     * <desc>
     *      查询可提现余额
     * <desc/>
     *
     * @param projectId 项目编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/23
     */
    @RequestMapping(path = "getBalance", method = RequestMethod.POST)
    @ResponseBody
    public Object getBalance(String projectId, String loginUserId, String token) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            loginUserId = request.getAttribute("loginUserId") == null ? null : request.getAttribute("loginUserId").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            //判断使用者是否有权限
            if (!this.checkRole(loginUserId,token)) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_USER_ROLE_ERR.getErrorCode());
            }
            //请求对象不能为空
            if(StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            PropertyBalanceVO result =
                    iPropertyWithdrawServiceClient.getBalance(projectId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_提现服务_查询可提现余额getBalance】查询可提现余额失败"), e);
        }
    }

    /**
     * <desc>
     *      查询自动提现信息
     * <desc/>
     *
     * @param projectId 项目编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/24
     */
    @RequestMapping(path = "getAutoWithdraw", method = RequestMethod.POST)
    @ResponseBody
    public Object getAutoWithdraw(String projectId, String loginUserId, String token) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            loginUserId = request.getAttribute("loginUserId") == null ? null : request.getAttribute("loginUserId").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            //判断使用者是否有权限
            if (!this.checkRole(loginUserId,token)) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_USER_ROLE_ERR.getErrorCode());
            }
            //请求对象不能为空
            if(StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyWithdrawServiceClient.getAutoWithdraw(projectId));
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_提现服务_查询自动提现信息getAutoWithdraw】查询自动提现信息失败"), e);
        }
    }

    /**
     * <desc>
     *      自动提现设置
     * <desc/>
     *
     * @param propertyAutoWithdrawDTO 自动提现信息
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/23
     */
    @RequestMapping(path = "setAutoWithdraw", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.AUTO_WITHDRAW_LOG_DESC)
    @ResponseBody
    public Object setAutoWithdraw(PropertyAutoWithdrawDTO propertyAutoWithdrawDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyAutoWithdrawDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyAutoWithdrawDTO.class, request);
            //判断使用者是否有权限
            if (!this.checkRole(propertyAutoWithdrawDTO.getLoginUserId(),propertyAutoWithdrawDTO.getToken())) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_USER_ROLE_ERR.getErrorCode());
            }
            //请求对象不能为空
            if(null == propertyAutoWithdrawDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getProjectId())) {//项目编号为空判断
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getAmount())) {//金额为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_AMOUNT_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getBankCardId())) {//银行卡ID为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_BANKCARDID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getCashRule())) {//提现规则为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_CASHRULE_EMPTY_ERR.getErrorCode());
            }
            if("2".equals(propertyAutoWithdrawDTO.getCashRule()) && StringUtils.isBlank(propertyAutoWithdrawDTO.getRuleDate())) {//提现日期为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_RULEDATE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getFunctionStatus())) {//状态为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_FUNCTIONSTATUS_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyAutoWithdrawDTO.getPayPassword())) {//支付密码为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_PAYPASSWORD_EMPTY_ERR.getErrorCode());
            }
            if(iPropertyWithdrawServiceClient.checkPayPassword(
                            propertyAutoWithdrawDTO.getProjectId(),propertyAutoWithdrawDTO.getPayPassword()) == 0) {//支付密码判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_PAYPASSWORD_WRONG_ERR.getErrorCode());
            }

            iPropertyWithdrawServiceClient.setAutoWithdraw(propertyAutoWithdrawDTO);
            return new MessageVO(propertyAutoWithdrawDTO.getBankCardId()+"|"+propertyAutoWithdrawDTO.getAmount(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_提现服务_自动提现设置setAutoWithdraw】自动提现设置余额失败"), e);
        }
    }

    /**
     * <desc>
     *      提现
     * <desc/>
     *
     * @param projectId 项目编号
     * @param bankCardId 银行卡ID
     * @param amount 提现金额
     * @param payPassword 支付密码
     * @param loginUserId 操作人ID
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/24
     */
    @RequestMapping(path = "withdraw", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.WITHDRAW_LOG_DESC)
    @ResponseBody
    public Object withdraw(String projectId,  String bankCardId,
                                 String amount, String payPassword,
                               String loginUserId, String token) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            loginUserId = request.getAttribute("loginUserId") == null ? null : request.getAttribute("loginUserId").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            bankCardId = request.getAttribute("bankCardId") == null ? null : request.getAttribute("bankCardId").toString();
            payPassword = request.getAttribute("payPassword") == null ? null : request.getAttribute("payPassword").toString();
            amount = request.getAttribute("amount") == null ? null : request.getAttribute("amount").toString();
            //判断使用者是否有权限
            if (!this.checkRole(loginUserId,token)) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_USER_ROLE_ERR.getErrorCode());
            }
            //请求对象不能为空
            if(StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            //查询项目是否可提现
            String financeStatus = iPropertyWithdrawServiceClient.getFinanceStatusByProjectId(projectId);
            if(financeStatus != null && "2".equals(financeStatus)) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_CAN_NOT_WITHDRAW_ERROR.getErrorCode());
            }
            if(StringUtils.isBlank(amount)) {//金额为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_AMOUNT_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(bankCardId)) {//银行卡ID为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_BANKCARDID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(payPassword)) {//支付密码为空判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_PAYPASSWORD_EMPTY_ERR.getErrorCode());
            }
            if(iPropertyWithdrawServiceClient.checkPayPassword(projectId,payPassword) == 0) {//支付密码判断
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_PAYPASSWORD_WRONG_ERR.getErrorCode());
            }
            if(iPropertyWithdrawServiceClient.checkUnionpayStatus() <= 0) {//判断银联支付状态
                return new MessageVO(PropertyErrorCodeEnum.UNIONPAY_STATUS_WRONG_ERR.getErrorCode());
            }
            PropertyProjectAmountVO propertyProjectAmountVO = iPropertyWithdrawServiceClient.getProjectAmountInfo(projectId);
            if (propertyProjectAmountVO == null ||
                    (new BigDecimal(propertyProjectAmountVO.getAllowedCashWithdrawl()).compareTo(new BigDecimal(amount)) == -1) ||
                    (new BigDecimal(propertyProjectAmountVO.getAccountAmount()).compareTo(new BigDecimal(amount)) == -1)) {
                return new MessageVO(PropertyErrorCodeEnum.WITHDRAW_AMOUNT_WRONG_ERR.getErrorCode());
            }
            BigDecimal handlingFee = iPropertyWithdrawServiceClient.withdraw(projectId,bankCardId,amount,loginUserId);
            if (handlingFee.compareTo(new BigDecimal("0")) >= 0) {
                String bankPhoneNum = iPropertyBankCardManageServiceClient.getProjectBankPhone(projectId);
                BankCardInfoVO bankCardInfoVO = iPropertyBankCardManageServiceClient.getBankCardInfo(bankCardId);
                String bankCardNo = bankCardInfoVO.getBankCardNo().substring(bankCardInfoVO.getBankCardNo().length()-4,bankCardInfoVO.getBankCardNo().length());
                Date dt = new Date();
                //最后的aa表示“上午”或“下午”    HH表示24小时制    如果换成hh表示12小时制
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String content = "尊敬的用户：您于"+sdf.format(dt)+"提现，金额"+amount+"元 手续费"+handlingFee.toString()+"元 提现到"+bankCardInfoVO.getOpenBankName()+bankCardNo+"账号，请稍后留意银行到账短信(云半径)";
                iIotTpSmsServiceClient.sendSmsCodeByPhone(bankPhoneNum,content);
            }
            return new MessageVO(projectId+"|"+bankCardId+"|"+amount,BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_提现服务_提现withdraw】提现失败"), e);
        }
    }

    /**
     * <desc>
     *      判断使用人员是否有权限
     * <desc/>
     *
     * @param loginUserId 操作人ID
     * @param token 登陆
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/28
     */
    private boolean checkRole(String loginUserId, String token) {
        PropertyUserCacheVO cacheUser = iPropertyUserServiceClient.checkCacheUser(loginUserId, token);
        if (cacheUser != null && cacheUser.getRoleId() !=null &&
                ("3".equals(cacheUser.getRoleId()) || "4".equals(cacheUser.getRoleId()) || "5".equals(cacheUser.getRoleId()))) {
            return true;
        }
        return false;
    }
}